package views

import (
	"errors"
	"log"
	"net/http"
	"strconv"
	"strings"

	"gitee.com/Yu-eng/Myproject/my-go-blog/common"
	"gitee.com/Yu-eng/Myproject/my-go-blog/service"
)

func (*HTMLApi) Category(w http.ResponseWriter, r *http.Request) {
	//处理 /c/1 参数
	categoryTemplate := common.Template.Category
	path := r.URL.Path
	//将路径转化为cid
	cIdStr := strings.TrimPrefix(path, "/c/")

	cId, err := strconv.Atoi(CIdStr)

	if err != nil {
		//出错在页面上写入
		categoryTemplate.WriteError(w, errors.New("不识别此请求路径!"))
		return
	}
	//这里实现分页的功能
	//处理表单,尝试转换为表单
	if err = r.ParseForm(); err != nil {
		log.Println("表单数据获取异常！", err)
		categoryTemplate.WriteError(w, errors.New("系统错误，请联系管理员！"))
		return
	}
	//尝试解析表单内的数据
	pageStr := r.Form.Get("page")
	//默认  空串时 page为1
	if pageStr == "" {
		pageStr = "1"
	}
	//每页显示的数量
	page, _ := strconv.Atoi(pageStr)
	pageSize := 10

	categoryResponse := service.GetPostsByCategoryId(cId, page, pageSize)
	categoryTemplate.WriteData(w, categoryResponse)
}
